package com.wzj.yygh.hosp.controller.admin;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzj.yygh.common.exception.YyghException;
import com.wzj.yygh.common.result.R;
import com.wzj.yygh.common.result.ResultCode;
import com.wzj.yygh.hosp.service.HospitalSetService;
import com.wzj.yygh.hosp.utils.MD5;
import com.wzj.yygh.model.hosp.HospitalSet;
import com.wzj.yygh.vo.hosp.HospitalSetQueryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

@Api(tags = "医院设置管理")
@RestController
@RequestMapping("/admin/hosp/hospitalSet")
//@CrossOrigin
public class HospitalSetController {

    //注入service
    @Autowired
    private HospitalSetService hospitalSetService;

    // http://localhost:8201/admin/hosp/hospitalSet/findAll

    //1 查询医院设置表所有信息
    @ApiOperation(value = "获取所有医院设置")
    @GetMapping("findAll")
    public R findAllHospitalSet() {
        //调用service的方法
        List<HospitalSet> list = hospitalSetService.list();
        return R.ok().data("list",list);
    }

    //2 逻辑删除医院设置
    @ApiOperation(value = "逻辑删除医院设置")
    @DeleteMapping("{id}")
    public R removeHospSet(
            @ApiParam(value = "医院id",required = true)
            @PathVariable Long id) {
        try {
            boolean flag = hospitalSetService.removeById(id);
            if(flag) {
                return R.ok().message("删除成功");
            } else {
                return R.error().message("删除失败").code(ResultCode.ERROR_DELETE);
            }
        } catch (Exception e) {
//            throw new RuntimeException(e);
            throw new YyghException(ResultCode.ERROR,"删除医院设置信息错误",e);
        }
    }

    //3 条件查询带分页
    @ApiOperation("分页查询")
    @PostMapping("post/{page}/{limit}")
    public R findPageHospSet1(
            @ApiParam(value = "当前页码",required = true)
            @PathVariable long page,
            @ApiParam(value = "每页记录数",required = true)
            @PathVariable long limit,
            @ApiParam(value = "查询对象")
            @RequestBody(required = false) HospitalSetQueryVo hospitalSetQueryVo) {
        //创建page对象，传递当前页，每页记录数
        Page<HospitalSet> pageInfo = new Page<>(page,limit);
        //构建条件
        QueryWrapper<HospitalSet> wrapper = new QueryWrapper<>();
        String hosname = hospitalSetQueryVo.getHosname();//医院名称
        String hoscode = hospitalSetQueryVo.getHoscode();//医院编号
        if(!StringUtils.isEmpty(hosname)) {
            wrapper.like("hosname",hospitalSetQueryVo.getHosname());
        }
        if(!StringUtils.isEmpty(hoscode)) {
            wrapper.eq("hoscode",hospitalSetQueryVo.getHoscode());
        }

        //调用方法实现分页查询
        IPage<HospitalSet> pageHospitalSet = hospitalSetService.page(pageInfo, wrapper);
        //返回结果
        return R.ok().data("rows",pageHospitalSet.getRecords()).data("total",pageHospitalSet.getTotal());
    }

    @ApiOperation("分页查询")
    @GetMapping("{page}/{limit}")
    public R findPageHospSet(
            @ApiParam(value = "当前页码",required = true)
            @PathVariable long page,
            @ApiParam(value = "每页记录数",required = true)
            @PathVariable long limit,
            @ApiParam(value = "查询对象")
            HospitalSetQueryVo hospitalSetQueryVo) {
        //创建page对象，传递当前页，每页记录数
        Page<HospitalSet> pageInfo = new Page<>(page,limit);
        //构建条件
        QueryWrapper<HospitalSet> wrapper = new QueryWrapper<>();
        String hosname = hospitalSetQueryVo.getHosname();//医院名称
        String hoscode = hospitalSetQueryVo.getHoscode();//医院编号
        if(!StringUtils.isEmpty(hosname)) {
            wrapper.like("hosname",hospitalSetQueryVo.getHosname());
        }
        if(!StringUtils.isEmpty(hoscode)) {
            wrapper.eq("hoscode",hospitalSetQueryVo.getHoscode());
        }

        //调用方法实现分页查询
        IPage<HospitalSet> pageHospitalSet = hospitalSetService.page(pageInfo, wrapper);
        //返回结果
        return R.ok().data("rows",pageHospitalSet.getRecords()).data("total",pageHospitalSet.getTotal());
    }

    //4 添加医院设置
    @ApiOperation("添加医院")
    @PostMapping("saveHospSet")
    public R saveHospSet(@RequestBody HospitalSet hospitalSet) {
        //设置状态 1 使用 0 不能使用
        hospitalSet.setStatus(1);
        //签名秘钥
        Random random = new Random();
        hospitalSet.setSignKey(MD5.encrypt(System.currentTimeMillis()+""+random.nextInt(1000)));
        //调用service
        boolean save = hospitalSetService.save(hospitalSet);
        if(save) {
            return R.ok().message("添加成功");
        } else {
            return R.error().message("添加失败");
        }
    }

    //5 根据id获取医院设置
    @ApiOperation("根据ID获取医院信息")
    @GetMapping("getHospSet/{id}")
    public R getHospSet(@PathVariable Long id) {
//        try {
//            //模拟异常
//            int a = 1/0;
//        }catch (Exception e) {
//            throw new YyghException("失败",201);
//        }

        HospitalSet hospitalSet = hospitalSetService.getById(id);
        return R.ok().data("item",hospitalSet);
    }

    //6 修改医院设置
    @ApiOperation("修改医院信息")
    @PutMapping("updateHospSet")
    public R updateHospitalSet(@RequestBody HospitalSet hospitalSet) {
        boolean flag = hospitalSetService.updateById(hospitalSet);
        if(flag) {
            return R.ok().message("修改成功");
        } else {
            return R.error().message("修改失败");
        }
    }

    //7 批量删除医院设置
    @ApiOperation("批量删除医院")
    @DeleteMapping("batchRemove")
    public R batchRemoveHospitalSet(@RequestBody List<Long> idList) {
        boolean result = hospitalSetService.removeByIds(idList);
        if (result){
            return R.ok().message("删除成功");
        }else {
            return R.error().message("删除失败");
        }
    }

    //8 医院设置锁定和解锁
    @ApiOperation("医院设置锁定和解锁")
    @PutMapping("lockHospitalSet/{id}/{status}")
    public R lockHospitalSet(@PathVariable Long id,
                                  @PathVariable Integer status) {
        //根据id查询医院设置信息
        /*
        HospitalSet hospitalSet = hospitalSetService.getById(id);
        //设置状态
        hospitalSet.setStatus(status);
        //调用方法
        hospitalSetService.updateById(hospitalSet);*/

        if (status !=0 && status != 1){
            return R.error().message("非法数据");
        }
        LambdaUpdateWrapper<HospitalSet> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(HospitalSet::getId,id).set(HospitalSet::getStatus,status);
        boolean update = hospitalSetService.update(updateWrapper);
        if (update){
            return R.ok().message(status == 1 ? "解锁成功" : "锁定成功");
        }else {
            return R.error().message("操作失败");
        }
    }

    //9 发送签名秘钥
    @PutMapping("sendKey/{id}")
    public R lockHospitalSet(@PathVariable Long id) {
        HospitalSet hospitalSet = hospitalSetService.getById(id);
        String signKey = hospitalSet.getSignKey();
        String hoscode = hospitalSet.getHoscode();
        // TODO 发送短信
        return R.ok().message("发送成功");
    }
}
